#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Created by master on 2017/3/5
import socket

import subprocess

ip_port = ("127.0.0.1", 9999)

sk = socket.socket()
sk.bind(ip_port)
sk.listen(5)  # 最大连接数

while True:
    print("server waiting...")
    conn, addr = sk.accept()  # 获取scoket实例和ip地址和端口

    while True:
        client_data = conn.recv(1024)  # socket 建议最大不超过8k
        if not client_data.decode(): break
        print("recv:", str(client_data, "utf8"))
        cmd = str(client_data).strip()
        cmd_call = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)

        cmd_result = cmd_call.stdout.read()
        if len(cmd_result) == 0:
            cmd_result = bytes("error", "utf8")
        ack_msg = bytes("CMD_RESULT_SIZE|%s" % len(cmd_result), "utf8")
        conn.send(ack_msg)  # 先发送文件长度信息
        client_ack = conn.recv(50)  # 防止粘包 让客户端确认
        if client_ack.decode() == "CLIENT_READY_TO_RECV":
            conn.send(cmd_result)

    conn.close()
